<template>
    <el-card class="my-20px">
        <filterComponent v-model:filter-data="filterData" @doSearch="handleSearch" />
    </el-card>
    <el-card>
        <tableComponent class="set-height" :table-header="tableHeader" :table-data="tableData" v-model:page-info="pageInfo"
            @pageChange="handlePageChange" @sort-change="sortMethod">
            <template #settings>
                <el-table-column fixed="right" label="操作" width="120">
                    <template #default="scope">
                        <el-button link type="primary" size="small" @click="toDetail(scope.row)">查看详情</el-button>
                    </template>
                </el-table-column>
            </template>
        </tableComponent>
    </el-card>
</template>
<script setup>
import { ref, onMounted, onActivated} from 'vue'
import filterComponent from '@/components/filterComponent/index.vue'
import tableComponent from '@/components/tableComponent/index.vue'
import { getWesureDetails, getInsureCompany } from '@/api/dashboard/weinsure.ts'
import { getdepartmentapi } from '@/api/api.ts'
import { getDealList, getDeptList, getSalesmanList, getProductList } from '@/api/clients/signClient.ts'
import { useRoute, useRouter } from 'vue-router'

const router = useRouter()

import dayjs from 'dayjs'

const startDate = dayjs().subtract(30, 'day') .format('YYYY-MM-DD')
const endDate = dayjs().format('YYYY-MM-DD')

const props = defineProps({
    insureType: {
        type: String,
        default: ''
    }
})

const filterData = ref({
    list: {
        deptId: {
            name: '所属分组',
            prop: 'deptId',
            value: '',
            placeholder: '请选择所属分组',
            type: 'selectDept',
            options: [],
            defaultAttrs: {
                label: 'deptName',
                value: 'deptId'
            },
            handleFocus: (item) => {
                // if (item.options?.length) return
                // getDeptList({
                //     type: 1
                // }).then(res => {
                //     item.options = res
                // })
            }, 
            handleChange: (item) => {
                filterData.value.list.salesId.value = ''
                filterData.value.list.salesId.options = []
            }
        },
        salesId: {
            name: '成员',
            clearOption: true,
            prop: 'saleId',
            value: '',
            placeholder: '请选择成员',
            type: 'select',
            options: [],
            defaultAttrs: {
                label: 'saleName',
                value: 'saleId'
            },
            handleFocus: (item) => {
                const value = filterData.value.list.deptId.value
                if (!value) {
                    ElMessage.warning({
                        message: '请先选择所属部门'
                    })
                    return
                }
                if (item.options?.length) return
                getSalesmanList({
                    auditStatus: 1,
                    deptId: value
                }).then(res => {
                    item.options = res
                })
            }
        },

        date: {
            name: '日期',
            prop: 'date',
            value: [startDate, endDate],
            initValue: [startDate, endDate],
            placeholder: '请选择日期',
            type: 'date',
            dateType: 'daterange',
            noClear: true,
            handleFocus: (item) => {

            },
            handleChange: (item) => {

            }
        },
        searchText: {
            name: '搜索',
            prop: 'searchText',
            value: '',
            placeholder: '请输入客户名称/负责人',
            type: 'input',
            inputType: 'text',
            handleFocus: (item) => {

            },
            handleChange: (item) => {

            },
            handleInput: (item) => {

            }
        },
    },
    buttonList: [
        // {
        //     icon: 'Plus',
        //     name: '新增行业',
        //     click: () => {
        //         addType.value = 'add'
        //         showAdd.value = true
        //         curItem.value = {}
        //     }
        // }
    ]
})

const pageInfo = ref({
    pageNum: 1,
    pageSize: 10,
    total: 0
})

const tableHeader = ref([
    {
        label: '客户名称',
        prop: 'companyName',
        width: 200,
    },
    {
        label: '商务负责人',
        prop: 'businessPrincipal',
    },
    {
        label: '所属分组',
        prop: 'deptName',
    },
    {
        label: '保司',
        prop: 'insureCompanyName',
    },
    {
        label: '投保人数',
        prop: 'numberOfInsured',
        sortable: 'customer'
    },
    {
        label: '保费',
        prop: 'premium',
        sortable: 'customer',
        style: {
            color: '#FF7642'
        }
    },
    {
        label: '投保时间',
        prop: 'insuredDate',
        sortable: 'customer'
    }
])

const sortOrder = ref('')

const tableData = ref([])

const sortMethod = ({ prop, order }) => {
    switch (prop) {
        case 'insuredDate':
            if (!order) {
                sortOrder.value = ''
            } else {
                sortOrder.value = order === 'ascending' ? 1 : 0
            }
            console.log(333, sortOrder.value)
            break
        case 'premium':
            if (!order) {
                sortOrder.value = ''
            } else {
                sortOrder.value = order === 'ascending' ? 3 : 2
            }
            break
        case 'numberOfInsured':
            if (!order) {
                sortOrder.value = ''
            } else {
                sortOrder.value = order === 'ascending' ? 5 : 4
            }
            break
    }
    getData()
}

const handleSearch = () => {
    getData()
}

const handlePageChange = () => {
    getData()
}

const toDetail = (row) => {
    const map = {
        dashboardDay: '/detailWeInsure',
        dashboardGroup: '/detailGroupInsure'
    }
    router.push({
        path: map[props.insureType],
        query: {
            id: btoa(row.dealId),
            companyId: btoa(row.companyId)
        }
    })
}

const createQuery = () => {
    const query = {}
    for (const key in filterData.value.list) {
        if (filterData.value.list[key].prop === 'date') {
            query.startTime = filterData.value.list[key].value?.length ? filterData.value.list[key].value[0] : ''
            query.endTime = filterData.value.list[key].value?.length ? filterData.value.list[key].value[1] : ''
        } else {
            query[filterData.value.list[key].prop] = filterData.value.list[key].value
        }
    }
    return query
}

const getData = () => {
    let insureCompanyType = ''
    if (props.insureType === 'dashboardGroup') {
        insureCompanyType = 'insure_type_tyrb'
    }
    getWesureDetails({
        ...createQuery(),
        pageSize: pageInfo.value.pageSize,
        pageNum: pageInfo.value.pageNum,
        sortOrder: sortOrder.value,
        insureCompanyType: insureCompanyType,
    }).then(async res => {
        tableData.value = res.list
        pageInfo.value.total = res.totalCount

        const query = {
            type: 1
        }
        if (props.insureType === 'dashboardGroup') {
            query.type = 3
        }
        const companyList = await getInsureCompany(query)
        tableData.value.forEach(i => {
            const cur = companyList.find(c => c.insurCompany === i.insureCompanyType)
            if(cur) {
                i.insureCompanyName = cur.name
            }
        })
    })
}

onMounted(() => {
    getData()
})
onActivated(() => {
    getData()
})
</script>
<style lang="scss" scoped>

</style>